#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"
#include <functional>
#include <iostream>
#include <string>

using json = nlohmann::json;

ChatServer::ChatServer(EventLoop* loop,
               const InetAddress& listenAddr,
               const string& nameArg)
    :_server(loop, listenAddr, nameArg) ,_loop(loop)
{
    _server.setConnectionCallback(std::bind(&ChatServer::OnConnection, this, std::placeholders::_1));
    _server.setMessageCallback(std::bind(&ChatServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    _server.setThreadNum(4);
}

void ChatServer::Start()
{
    _server.start();
}

void ChatServer::OnConnection(const TcpConnectionPtr& pt)
{
    // 客户端断开连接
    if (!pt->connected()) {
        ChatService::GetInstance()->ClientCloseException(pt);
        pt->shutdown();
    }
}

void ChatServer::OnMessage(const TcpConnectionPtr& pt, Buffer *buffer, Timestamp time)
{
    string buf = buffer->retrieveAllAsString();
    // 数据的反序列化
    json js = json::parse(buf);
    // 通过js["msgid"] 来获取业务hanlder, 解耦网络模块和业务模块的代码
    auto msgHandler = ChatService::GetInstance()->GetHandler(js["msgid"].get<int>());
    msgHandler(pt, js, time);
}